package cn.craftyun.yunexam.service.impl;

import cn.craftyun.yunexam.entity.ExamStatus;
import cn.craftyun.yunexam.mapper.ExamStatusMapper;
import cn.craftyun.yunexam.service.ExamAnswerService;
import cn.craftyun.yunexam.service.ExamStatusService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ExamStatusServiceImpl extends ServiceImpl<ExamStatusMapper, ExamStatus> implements ExamStatusService {
    @Resource
    private ExamAnswerService examAnswerService;

    @Override
    public ExamStatus getExamStatus(Long examId, Long userId) {
        Wrapper<ExamStatus> wrapper = new QueryWrapper<ExamStatus>()
                .eq("user_id", userId)
                .eq("exam_id", examId)
                .last("limit 1");
        return getBaseMapper().selectOne(wrapper);
    }

    @Override
    public void isExamGetOn(Long examId, Long userId) {
        ExamStatus examStatus = this.getExamStatus(examId, userId);
        if (examStatus == null) {
            throw new RuntimeException("用户未参加考试或考试状态异常");
        }
        if (examStatus.getStatus() == 1) {
            throw new RuntimeException("试卷已提交");
        }
        if (examStatus.getEndTime() < new Date().getTime() / 1000) {
            throw new RuntimeException("考试时间已到");
        }
    }

    @Override
    public void submitExam(Long examId, Long userId) {
        // 计算最终分数
        Integer endScore = examAnswerService.getExamScore(examId, userId);
        // 开始锁定试卷
        Wrapper<ExamStatus> wrapper = new UpdateWrapper<ExamStatus>()
                .eq("user_id", userId)
                .eq("exam_id", examId)
                .set("status", 1)
                .set("end_score", endScore);
        if (getBaseMapper().update(null, wrapper) == 0) {
            throw new RuntimeException("提交试卷失败");
        }
    }

    @Override
    public boolean removeByExamId(Long examId) {
        Wrapper<ExamStatus> wrapper = new UpdateWrapper<ExamStatus>().eq("exam_id", examId);
        return getBaseMapper().delete(wrapper) > 0;
    }

    @Override
    public boolean removeByUserId(Long userId) {
        Wrapper<ExamStatus> wrapper = new UpdateWrapper<ExamStatus>().eq("user_id", userId);
        return getBaseMapper().delete(wrapper) > 0;
    }

    @Override
    public boolean removeByPaperId(Long paperId) {
        return getBaseMapper().deleteByPaperId(paperId) > 0;
    }

    @Override
    public List<Map<String, Object>> getExamStatus(Long examId) {
        return getBaseMapper().getExamStatus(examId);
    }
}
